<template>
  <view>

    <u-modal
        :show="modal.byRemark.show"
        :showConfirmButton="false"
        :title="modal.byRemark.title"
        @confirm="modal.byRemark.confirm"
        @close="modal.byRemark.close"
        :closeOnClickOverlay="true"
    >
      <view style="text-align: center;">
        <view style="margin-top: 20rpx">
          <text style="color: #747d8c">{{modal.byRemark.content}}</text>
        </view>
      </view>
    </u-modal>

    <u-popup
        mode="bottom"
        :round="10"
        :show="modal.byTemplate.show"
        :showConfirmButton="false"
        :title="modal.byTemplate.title"
        :closeOnClickOverlay=true
        @close="modal.byTemplate.close()"
    >
      <view style="margin: 10px 0;Letter-spacing: 3px">
        <u--text
            type="info"
            bold="true"
            text="编辑运费模板"
            align="center"
            size="20"
        >
        </u--text>
      </view>

      <view style="margin: 10px 10px">
        <u--form labelPosition="left" labelWidth="auto">

          <u-form-item label="备注 : " borderBottom>
            <u--input
                v-model="modal.byTemplate.item.remark"
                :clearable=true
            >
            </u--input>
          </u-form-item>

          <u-form-item label="选中区域运费(单位/元) :" borderBottom>
            <u--input
                v-model="modal.byTemplate.item.areaPrice"
                type="digit"
                placeholder="输入选中区域运费">
            </u--input>
          </u-form-item>

          <u-form-item label="其他区域运费(单位/元) :" borderBottom>
            <u--input
                v-model="modal.byTemplate.item.defaultPrice"
                type="digit"
                placeholder="输入其他区域运费">
            </u--input>
          </u-form-item>

          <view>
            <view style="margin: 10px 0">
              <u--textarea
                  v-model="modal.byTemplate.item.locationText"
                  autoHeight
                  disabled
                  border="surround"
              >
              </u--textarea>
            </view>
            <u-button
                type="success"
                shape="circle"
                @click="options.locationIds.open()"
            >
              点击编辑运费模板地址
            </u-button>
          </view>

        </u--form>
      </view>

      <view style="margin: 10px 5px 0 5px">
        <u-row gutter="2">
          <u-col :span="4">
            <u-button
                plain
                type="warning"
                text="返回"
                @click="modal.byTemplate.close()"
            >
            </u-button>
          </u-col>
          <u-col :span="4">
            <u-button
                plain
                type="primary"
                text="清空"
                @click="modal.byTemplate.def()"
            >
            </u-button>
          </u-col>
          <u-col :span="4">
            <u-button
                plain
                type="success"
                @click="commit"
                text="提交"
            >
            </u-button>
          </u-col>
        </u-row>
      </view>
    </u-popup>

    <!-- 提交搜索弹窗 -->
    <u-popup
        :show="condition.show"
        :round="10"
        mode="bottom"
        :direction=0
        :closeable=true
        @close="condition.close()"
    >
      <view>
        <view style="text-align: center;margin: 10px 0 20px 0 ">
          <text style="font-size: 34rpx;font-weight: bold">
            填充筛选条件(不填的条件不参与判断)
          </text>
        </view>
        <view style="margin: 10px 10px">
          <u--form labelPosition="left" labelWidth="auto">

            <u-form-item label="备注包含:">
              <u--input
                  v-model="condition.data.remark"
                  :clearable=true
                  border="bottom"
              >
              </u--input>
            </u-form-item>

            <u-form-item label="创建时间范围:">
              <view style="z-index:10000">
                <uni-datetime-picker
                    hide-second="true"
                    type="datetimerange"
                    v-model="condition.data.createTime.value"
                    @change="condition.data.createTime.change"
                    rangeSeparator="至" />
              </view>
            </u-form-item>

            <view>
              <u-row gutter="1">
                <u-col :span="6">
                  <u-button type="success" text="清空" @click="condition.def()"></u-button>
                </u-col>
                <u-col :span="6">
                  <u-button type="primary" text="搜索" @click="condition.search()"></u-button>
                </u-col>
              </u-row>
            </view>
          </u--form>
        </view>
      </view>
    </u-popup>

    <!-- 排序条件选择器 -->
    <u-picker
        :show="listSortPicker.show"
        :columns="listSortPicker.options"
        @confirm="listSortPicker.confirm"
        @close="listSortPicker.close"
        @cancel="listSortPicker.close"
        title="选择某属性点击确定即可"
        :closeOnClickOverlay=true
        keyName="label"
    >
    </u-picker>


    <view>
      <view style="margin: 20rpx 0 0 20rpx">
        <view style="display: inline-block;margin-right: 10rpx">
          <u-button shape="circle" size="medium" @click="condition.open()">
            <text style="font-size: 24rpx;
            font-weight: bold;
            color: #8c7d7d;padding: 0 20rpx">
              条件搜索
            </text>
          </u-button>
        </view>

        <view style="display: inline-block;margin-right: 10rpx">
          <u-button shape="circle" size="medium" @click="listSortPicker.open()">
            <text style="font-size: 24rpx;
            font-weight: bold;
            color: #8c7d7d;padding: 0 20rpx">
              表格排序
            </text>
          </u-button>
        </view>

        <view style="
          display: inline-block;
          float: right;
          margin-right: 26rpx"
        >
          <u-button shape="circle" size="medium"
                    @click="modal.byTemplate.open()">
            <text style="font-size: 24rpx;
            font-weight: bold;
            color: #8c7d7d;padding: 0 20rpx">
              添加运费模板
            </text>
          </u-button>
        </view>
      </view>
    </view>

    <view
        style="margin: 20rpx 30rpx"
    >
     <uni-table
         border
         stripe
         :loading="table.loading"
         emptyText="您当前还没有运费信息噢."
     >
       <!-- 表头行 -->
       <uni-tr>
         <uni-th align="center">
           <text class="table-th-font">备注</text>
         </uni-th>
         <uni-th align="center">
           <text class="table-th-font">状态</text>
         </uni-th>
         <uni-th align="center" width="200">
           <text class="table-th-font">创建时间</text>
         </uni-th>
         <uni-th align="center">
           <text class="table-th-font">指定区域运费(单位/元)</text>
         </uni-th>
         <uni-th align="center">
           <text class="table-th-font">其他区域运费(单位/元)</text>
         </uni-th>
         <uni-th align="center" width="180">
           <text class="table-th-font">操作</text>
         </uni-th>
       </uni-tr>

       <!-- 数据行 -->
       <uni-tr v-for="(item,index) in table.data " :key="index">
         <uni-td align="center">
           <text id="text-flow" @click="modal.byRemark.open(item.remark)">{{item.remark}}</text>
         </uni-td>

         <uni-td align="center">
           <rich-text :nodes="style.status(item.status)"></rich-text>
         </uni-td>

         <uni-td align="center">
           <text>{{service.style.time(item.createTime,6)}}</text>
         </uni-td>

         <uni-td align="center">
           <text>{{item.areaPrice}}</text>
         </uni-td>

         <uni-td align="center">
           <text>{{item.defaultPrice}}</text>
         </uni-td>

         <uni-td align="center">
           <button
               class="operation-btn"
               type="primary"
               size="mini"
               @click="modal.byTemplate.open(item)"
           >修改</button>
           <button
               class="operation-btn"
               type="warn"
               size="mini"
               @click="deleteItem(item.id, index)"
           >删除</button>
         </uni-td>

       </uni-tr>
     </uni-table>
    </view>

    <!-- 分页 -->
    <view
        style="text-align: center"
    >
      <view style="display: inline-block;margin: 0 8rpx">
        <page-pagination
            :total="table.total"
            :pageSize="table.pageSize"
            :showAround="true"
            :btnText="true"
            :forceEllipses="true"
            @change="table.setPageNo">
        </page-pagination>
      </view>
    </view>
    <!-- 选择运费模板区域 -->
    <BaTreePicker
        ref="locationIds"
        :multiple=true
        title="编辑运费模板区域"
        valueKey="id"
        textKey="name"
        childrenKey="subList"
        @select-change="options.locationIds.ok"
    />
    <!--自己封装的提示器-->
    <popup ref="popup" />
  </view>
</template>

<script>
import service from "@/utils/service";
import BaTreePicker from "@/merchant/comm/ba-tree-picker/ba-tree-picker"
import popup from "@/merchant/my/my-popup"
export default {
  components: {
    BaTreePicker,
    popup
  },
  data() {
    let _vm = this;
    return {
      service: service,
      table: {
        loading: true,
        total: 0,
        pageSize: 10,
        pageNo: 1,
        data: [],
        setPageNo(v) {
          _vm.table.pageNo = v
          _vm.getList();
        },
      },
      style: {
        status(v){
          switch (v){
            case 0:
              return '<span style="color:#7bed9f">正常</span>'
            case -1:
              return '<span style="color:#ff6b81">冻结</span>'
          }
        }
      },
      /* 模态窗相关对象 */
      modal:{
        /* 备注模态窗 */
        byRemark: {
          show: false,
          title : '备注信息',
          content: '',
          open(content){
            _vm.modal.byRemark.content = content
            _vm.modal.byRemark.show = true
          },
          confirm(){
            _vm.modal.byRemark.close();
          },
          close() {
            _vm.modal.byRemark.show = false
          },
        },
        /* 编辑模板 */
        byTemplate: {
          show: false,
          title: '编辑运费模板',
          target: 'add',
          item: {
            id: '',
            remark: '',
            locationIds: [],
            locationText: '',
            areaPrice: '',
            defaultPrice: '',
          },
          async open(item = undefined){
            if(!service.check.isNull(item)){
              /* 如果是上次是添加则清空 */
              if(_vm.modal.byTemplate.target !== 'update'){
                _vm.modal.byTemplate.target = 'update'
                _vm.modal.byTemplate.def();
              }
              _vm.modal.byTemplate.item = item
              _vm.modal.byTemplate.item.locationText = await _vm.getParentNamesByIds(item.locationIds);
            }else{
              if(_vm.modal.byTemplate.target !== 'add'){
                _vm.modal.byTemplate.target = 'add'
                _vm.modal.byTemplate.def();
              }
            }
            _vm.modal.byTemplate.show = true
          },
          def(){
            _vm.modal.byTemplate.item = {
              id: '',
              remark: '',
              locationIds: [],
              locationText: '',
              areaPrice: '',
              defaultPrice: '',
            }
          },
          close() {
            _vm.modal.byTemplate.show = false
          },
        }
      },
      // 表格排序选择器
      listSortPicker:{
        show: false,
        // 排序字段
        sortKey: null,
        // 排序规则 1 正序 -1 倒序
        sort: -1,
        options: [
          [
            {label: '默认', key: null},
            {label: '指定区域运费', key: 'area_price'},
            {label: '其他运费运费', key: 'default_price'},
          ],
          [
            {label: '从小到大', value: 1},
            {label: '从大到小', value: -1},
          ],
        ],
        // 确认回调
        confirm(v){
          let me = _vm.listSortPicker;
          console.log("表格排序选项结果 : ", v)
          me.show = false;
          // 默认
          if (v.value[0].key === null) {
            me.sort = v.value[1].value;
          }else{
            me.sortKey = v.value[0].key;
          }
          me.sort = v.value[1].value;
          this.getList();
        },
        close(){
          _vm.listSortPicker.show = false;
        },
        open(){
          _vm.listSortPicker.show = true;
        }
      },
      /* 条件筛选对象 */
      condition:{
        show: false,
        open(){
          _vm.condition.show = true;
        },
        close(){
          _vm.condition.show = false;
        },
        data: {
          /* 运费模板备注 */
          remark: '',
          /* 创建时间范围 */
          createTime: {
            value:[],
            change(e){
              console.log("选中创建时间 : ", e)
            }
          }
        },
        def(){
          _vm.condition.data.remark= ''
          _vm.condition.data.createTime.value = []
          _vm.condition.search();
        },
        search(){
          console.log("点击搜索 条件 : ", _vm.condition.data)
          _vm.condition.close();
          _vm.getList();
        }
      },
      /* 选项相关对象 */
      options: {
        /* 运费模板区域 */
        locationIds: {
          ops: [],
          ok(values, names) {
            console.log("选中支持配送地址 :")
            console.log("ids : ", values, names)
            _vm.modal.byTemplate.item.locationText = names;
            if (values.length === 0) {
              _vm.modal.byTemplate.item.locationText = '';
              _vm.modal.byTemplate.item.locationIds = [];
              return
            }
            _vm.getSubIdListByParentId(values, {
              ok: function(v) {
                _vm.modal.byTemplate.item.locationIds = v;
                _vm.$refs.locationIds.setSelectedData(
                    service.copy(_vm.modal.byTemplate.item.locationIds))
              }
            })
          },
          open() {
            _vm.$refs.locationIds._show();
          }
        },
      }
    }
  },
  methods: {

    getList(){
      let _t = this;
      let data = {}
      data.pageNo = this.table.pageNo
      data.pageSize = this.table.pageSize
      // 如果有排序字段添加排序字段
      if(this.listSortPicker.sortKey !== null){
        data.sortKey = this.listSortPicker.sortKey;
      }
      if(this.listSortPicker.sort !== null){
        data.sort = this.listSortPicker.sort;
      }
      // 追加条件字段
      if(!service.check.isNull(_t.condition.data.remark)){
        data.remark = _t.condition.data.remark
      }
      if(!service.check.isNull(_t.condition.data.createTime.value)){
        data.createTimeScope = JSON.stringify(_t.condition.data.createTime.value);
      }
      this.$axios({
        url: "merchant/merchantFreightTemplate/list",
        method: "post",
        data: data,
        header: {
          "Authorization": this.token,
          "Content-type": this.contentType,
          "type": "merchantsToken"
        },
      }).then(res => {
        console.log(" merchant/merchantFreightTemplate/list :  ",res)
        if(res.code === 0){
          _t.table.data = res.result.list;
          _t.table.pageNo = res.result.pageNo;
          _t.table.total = res.result.total;
        }
      }).finally(() => {
        _t.table.loading = false;
      })
    },

    /* 根据地址 父级 id列表 获取 最子级id*/
    getSubIdListByParentId(pIds, okBack) {
      let _t = this;
      this.$axios({
        url: 'system/sysLocation/getSubIdByPidList',
        method: 'post',
        data: {
          pIds: pIds
        }
      }).then(res => {
        console.log('system/sysLocation/getSubIdByPidList : ', res)
        if (res.code === 0) {
          okBack["ok"](res.result);
        } else {
          _t.$refs.popup.error(res.message);
        }
      })
    },
    /* 获取地址分类树信息 */
    getLocationTree() {
      let _t = this
      this.$axios({
        url: 'merchant/merchantGroupGoods/locationTree',
        method: 'post',
        header: {
          "Authorization": this.token,
          "Content-type": this.contentType,
          "type": "merchantsToken"
        },
      }).then(res => {
        if (res.code === 0) {
          _t.options.locationIds.ops = service.copy(res.result)
          _t.$refs.locationIds.setLocalData(_t.options.locationIds.ops)
        }
      })
    },

    /* 根据地区id 获取 最父级名称列表字符串 按 '/' 分割 */
    getParentNamesByIds(ids){
      return new Promise((resolve,reject)=> {
        let _t = this;
        this.$axios({
          url: 'system/sysLocation/getParentNamesByIds',
          method: 'post',
          data:{
            ids: ids
          }
        }).then(res => {
          console.log(" merchant/merchantGroupGoods/getParentNamesByIds :  " ,res)
          if(res.code === 0){
            resolve(res.result);
          }else{
            reject(res.result);
          }
        })
      })
    },

    /* 提交 添加 或 修改 */
    commit(){
      let _t = this;
      if(_t.checkParam()){
        return true;
      }
      let check = service.check;
      let temp = _t.modal.byTemplate.item;
      let data = {}
      if(!check.isNull(temp.id)){
        data.id = temp.id
      }
      data.remark = temp.remark
      data.locationIds = service.arrToString(temp.locationIds,",");
      data.areaPrice = temp.areaPrice;
      data.defaultPrice = temp.defaultPrice;
      uni.showLoading({
        title: '提交中.....',
        mask: true
      })
      this.$axios({
        url: "merchant/merchantFreightTemplate/add",
        method: "post",
        data: data,
        header: {
          "Authorization": this.token,
          "Content-type": this.contentType,
          "type": "merchantsToken"
        },
      }).then(res => {
        console.log(" merchant/merchantFreightTemplate/add :  ",res)
        if(res.code === 0){
          _t.getList();
          _t.$refs.popup.success("提交成功")
        }else{
          _t.$refs.popup.error("提交失败 : " + res.result)
        }
      }).finally(() => {
        _t.modal.byTemplate.close();
        _t.modal.byTemplate.def();
        uni.hideLoading();
      })
    },

    /* 删除模板 */
    deleteItem(id, index){
      let _t = this
      uni.showLoading({
        title: '提交中....',
        mask: true
      })
      this.$axios({
        url: "merchant/merchantFreightTemplate/remove",
        method: "post",
        data: {
          id: id
        },
        header: {
          "Authorization": this.token,
          "Content-type": this.contentType,
          "type": "merchantsToken"
        },
      }).then(res => {
        console.log(" merchant/merchantFreightTemplate/add :  ", res)
        if(res.code === 0){
          _t.$refs.popup.success("删除成功")
          _t.table.data.splice(index, 1)
        }else{
          _t.$refs.popup.error(res.result)
        }
      }).finally(() => {
        uni.hideLoading()
      })
    },

    /* 校验参数 */
    checkParam(){
      let _t = this;
      let item = service.copy(this.modal.byTemplate.item);

      if(_t.modal.byTemplate.target === 'update'){
        if(service.check.isNull(item.id)){
          uni.showToast({title: '提交的数据丢失,请重试', icon:'none'})
          return true;
        }
      }

      if(service.check.isNull(item.remark)){
        uni.showToast({title: '请填写备注', icon:'none'})
        return true;
      }

      if(!service.check.isNumber(item.areaPrice)){
        uni.showToast({title: '选中区域运费金额必须为数字', icon:'none'})
        return true;
      }else if (service.check.isDecimalOutBounds(item.areaPrice,2)){
        uni.showToast({title: '选中区域运费金额,必须精确到分(只保留两位小数)', icon:'none'})
        return true;
      }

      if(!service.check.isNumber(item.defaultPrice)){
        uni.showToast({title: '其他区域运费金额必须为数字', icon:'none'})
        return true;
      }else if (service.check.isDecimalOutBounds(item.defaultPrice,2)){
        uni.showToast({title: '其他区域运费金额,必须精确到分(只保留两位小数)', icon:'none'})
        return true;
      }

      if(service.check.isNull(item.locationIds)){
        uni.showToast({title: '请编辑运费模板地址', icon:'none'})
        return true;
      }
      console.log("参数校验通过");
      return false;
    }
  },
  onLoad() {
    // 获取图像地址前缀
    this.imgApi = this.$reqConfig.URLIMAGE
    // 获取请求头类型
    this.contentType = this.$reqConfig.CONTENTTYPE + ";+charset=UTF-8"
    // 获取token
    this.token = uni.getStorageSync("merchantsToken").token
    this.getLocationTree()
  },
  onShow() {
    this.getList()
  }

}
</script>

<style>
.table-th-font{
  color: #1c6f5c;
}
/*表头样式*/
.uni-table-th {
  background-color: #eff8ff;
  border: 1px #EBEEF5 solid;
}
.uni-table-td {
  font-size: 15px !important;
}
.uni-fab__item-text {
  font-size: 24rpx !important;
}
.operation-btn{
  margin: 2rpx 4rpx;
}
#text-flow{
  display: -webkit-box; /*弹性伸缩盒子模型显示*/
  -webkit-box-orient: vertical; /*排列方式*/
  -webkit-line-clamp: 1; /*显示文本行数(这里控制多少行隐藏)*/
  overflow: hidden; /*溢出隐藏*/
}
/*表单下划线*/
.u-line.data-v-727e452e {
  border-bottom-width: 8rpx !important;
}
/*表单 label*/
.u-form-item__body__left__content__label.data-v-067e4733 {
  font-size: 30rpx;
  font-weight: bold;
}
</style>
